public without sharing class InstrumentPolicyDividedUtil {
    
    /*
    *拆分仪器销售政策到任务量 
    * pid 仪器销售政策id 
    */

    public static String  divideToTask(String pid){
        InstrumentPolicy__c ip = null;

    	List<InstrumentMarketingPolicy__c> itrpList   = null ;
    	try {
            ip = [select Id ,isDivded__c ,Opportunity__c , Company__c, Account__c , Active__c , TerminalCustomer__c from InstrumentPolicy__c where Id=:pid];
    	     itrpList = [select Id ,AmountPurchased__c,StartDate__c,EndDate__c,CooperationPeriod__c,ReturnServiceFee__c,ReturnServiceFeeRentalFee__c, 
    	     Quantity__c ,Category1__c,Category2__c ,Brand__c ,Account__c ,TerminalAccunt__c from InstrumentMarketingPolicy__c where MarketingPolicy__c =:pid];
    	}catch (Exception e) {}
    	if(ip == null) return '参数异常!';

    	if(ip.isDivded__c == true) return '该政策已经拆分!';
        if(ip.Active__c !=  true ) return '未生效不能拆分!';
        
    	 //3.找到任务量追踪总表; 无则 新建任务量追踪总表
        CooperationStandard__c cs  = null ;
        try{
             cs =  [select Id  from CooperationStandard__c  where NewData__c = true 
            and Account__c =:ip.Account__c and TerminalCustomer__c =:ip.TerminalCustomer__c ]; 
        }catch(Exception e){
            cs =  new CooperationStandard__c();
            cs.Account__c = ip.Account__c;
            cs.TerminalCustomer__c = ip.TerminalCustomer__c;
            cs.NewData__c = true; //标记是新生成的任务量主表

          

        }
        //4.查找已经存在的任务量
        /*Map<String,TaskAmount__c> exTaskMap = new Map<String,TaskAmount__c>();
        for(TaskAmount__c ta :[select Id,Category1__c,Category2__c,Brand__c,Year__c,Month__c , AssignAmount__c ,ReturnServiceFee__c, ReturnServiceFeeRentalFee__c  from TaskAmount__c where Standers__r.TerminalCustomer__c =:itrp.TerminalAccunt__c 
        and Standers__r.Account__c =:itrp.Account__c and  Standers__r.NewData__c = true  and Origin__c ='销售政策' ]){
			String key = ta.Category1__c +'_'+ta.Brand__c +'_'+ta.Category2__c + '_'+ta.Year__c + '_'+ ta.Month__c;
			exTaskMap.put(key, ta);
        }*/

        Date minStartDate = null;
        Date maxEndDate = null; 

    	List<TaskAmount__c> tmp = new List<TaskAmount__c>();

        for ( InstrumentMarketingPolicy__c itrp: itrpList) {

            if(itrp.Quantity__c == null  ) return '销售政策数量不能为空!';
            if(itrp.CooperationPeriod__c == null ) return '销售政策合作年限不能为空!';
            if(itrp.StartDate__c == null ) return '销售政策合作开始日期不能为空!';
            if(itrp.Account__c == null ) return '销售政策开票客户不能为空!';
            if(itrp.TerminalAccunt__c == null ) return '销售政策终端客户不能为空!';
            if(itrp.ReturnServiceFee__c == null ) return '返维修服务费单台仪器采购金额标准(≥万元/年/不含税)不能为空!';
            if(itrp.ReturnServiceFeeRentalFee__c == null ) return '返维修服务费和租赁费单台仪器采购金额标准(≥万元/年/不含税)能为空!';
            
            minStartDate =  (  minStartDate == null ? itrp.StartDate__c : ( itrp.StartDate__c == null ? minStartDate : minStartDate.daysBetween(itrp.StartDate__c) > 0 ? minStartDate : itrp.StartDate__c  )  ) ;
            maxEndDate =  (  maxEndDate == null ? itrp.EndDate__c : ( itrp.EndDate__c == null ? maxEndDate : maxEndDate.daysBetween(itrp.EndDate__c) > 0 ?itrp.EndDate__c  : maxEndDate  )  ) ;

        	for(Integer i = 0 ; i <  Integer.valueOf(itrp.CooperationPeriod__c) * 12 ; i ++){
        		
        		TaskAmount__c ta = new TaskAmount__c();

        		ta.AssignAmount__c = itrp.AmountPurchased__c  * itrp.Quantity__c / 12  / 10000.0;
                ta.ReturnServiceFee__c = itrp.ReturnServiceFee__c * itrp.Quantity__c / 12 ;
                ta.ReturnServiceFeeRentalFee__c = itrp.ReturnServiceFeeRentalFee__c * itrp.Quantity__c / 12 ;


        		Date  d = itrp.StartDate__c.addMonths(i);

        		ta.Year__c = String.valueOf(d.year())+'年';
        		ta.Month__c = String.valueOf(d.month());
        		ta.Origin__c = '销售政策';
        		ta.Category1__c = itrp.Category1__c ;
        		ta.Category2__c = itrp.Category2__c ;
        		ta.Brand__c = itrp.Brand__c ;
        		ta.EquipmentPolicy__c = itrp.Id;
    			//String key = ta.Category1__c +'_'+ta.Brand__c +'_'+ta.Category2__c + '_'+ta.Year__c + '_'+ ta.Month__c;
    			/*if(exTaskMap.containsKey(key)){
    				ta.Id = exTaskMap.get(key).Id;
    				ta.AssignAmount__c += exTaskMap.get(key).AssignAmount__c;
                    ta.ReturnServiceFee__c += exTaskMap.get(key).ReturnServiceFee__c;
                    ta.ReturnServiceFeeRentalFee__c +=  exTaskMap.get(key).ReturnServiceFeeRentalFee__c;
    			}*/
        		tmp.add(ta);
        	}
        }

        cs.StartingDate__c =  cs.StartingDate__c == null ? minStartDate :  cs.StartingDate__c;

        cs.EndingDate__c = cs.EndingDate__c == null ? maxEndDate : (maxEndDate == null ? cs.EndingDate__c : maxEndDate.daysBetween(cs.EndingDate__c) > 0  ? cs.EndingDate__c : maxEndDate );

    	SavePoint sp = Database.setSavepoint();
    	try {
    	    if(cs.Id == null )insert  cs ; 
    	    for (TaskAmount__c ta :tmp  ) {
    	    	ta.Standers__c = cs.Id ;
    	    }
    	    if(tmp.size() > 0 )upsert  tmp;
    	    ip.isDivded__c = true;
    	    update ip ;
    	    return 'ok';

    	}catch (Exception e) {
    	    Database.rollback(sp);
    	    return '保存错误!'+e.getMessage() +' '+e.getStackTraceString();
    	}
    	
    	

    }
}